<template>
  <div>
    <!-- 查询功能 -->
    <div class="card" style="margin-bottom: 5px">
      <el-input
          v-model="data.content"
          prefix-icon="Search"
          style="width: 240px; margin-right: 10px"
          placeholder="请输入学生姓名查询"
      ></el-input>
      <el-select v-model="data.selectedClassId" placeholder="请选择班级" style="width: 180px; margin-right: 10px">
        <el-option value="" label="全部班级"></el-option>
        <el-option v-for="item in data.classList" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <el-select v-model="data.chooseStatus" placeholder="请选择回复状态" style="width: 180px; margin-right: 10px">
        <el-option value="" label="全部回复"></el-option>
        <el-option value="已回复" label="已回复"></el-option>
        <el-option value="待回复" label="待回复"></el-option>
      </el-select>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <!-- 批量删除和新增按钮 -->
    <div class="card" style="margin-bottom: 5px">
      <el-button type="danger" plain @click="delBatch" v-if="data.user.role !== 'STUDENT'">批量删除</el-button>
      <el-button type="success" plain style="margin-left: 10px" @click="handleAdd" v-if="data.user.role === 'STUDENT'">上传举报或反馈信息</el-button>
    </div>

    <!-- 表格展示 -->
    <div class="card" style="margin-bottom: 5px">
      <el-table stripe :data="data.tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="studentName" label="学生姓名" />
        <el-table-column prop="content" label="反馈或举报内容" />
        <el-table-column label="附件" width="150">
          <template v-slot="scope">
            <a v-if="scope.row.attachment" :href="scope.row.attachment" target="_blank">下载附件</a>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="replyContent" label="回复内容" />
        <el-table-column prop="status" label="回复状态">
          <template #default="scope">
            <el-tag type="warning" v-if="scope.row.status === '待回复'">待回复</el-tag>
            <el-tag type="success" v-if="scope.row.status === '已回复'">已回复</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" v-if="data.user.role!=='STUDENT'">
          <template v-slot="scope">
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <el-button
                  plain
                  type="primary"
                  @click="handleReply(scope.row)"
              >
                回复
              </el-button>
              <el-button
                  type="danger"
                  circle
                  :icon="Delete"
                  @click="del(scope.row.id)"
              ></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="card" v-if="data.total">
      <el-pagination
          @current-change="load"
          background
          layout="prev, pager, next"
          :page-size="data.pageSize"
          v-model:current-page="data.pageNum"
          :total="data.total"
      />
    </div>

    <!-- 添加举报信息对话框 -->
    <el-dialog
        title="添加举报信息"
        v-model="data.addFormVisible"
        width="40%"
        destroy-on-close
    >
      <el-form ref="addForm" :model="data.addForm" label-width="70px" style="padding: 20px">
        <el-form-item label="内容">
          <el-input
              type="textarea"
              rows="4"
              v-model="data.addForm.content"
              placeholder="请输入举报内容"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
              class="upload-demo"
              ref="upload"
              :action="uploadUrl"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :limit="1"
              :accept="'.zip,.rar'"
          >
            <el-button size="small" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="data.addFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAdd">确定</el-button>
      </template>
    </el-dialog>

    <!-- 回复举报内容对话框 -->
    <el-dialog title="回复举报内容" v-model="data.replyFormVisible" width="40%" destroy-on-close>
      <el-form ref="replyForm" :model="data.replyForm" label-width="70px" style="padding: 20px">
        <el-form-item label="回复内容">
          <el-input
              type="textarea"
              rows="4"
              v-model="data.replyForm.replyContent"
              placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="data.replyFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveReply">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete } from "@element-plus/icons-vue";

const data = reactive({
  content: "",
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  addFormVisible: false,
  addForm: {
    content: "",
    attachment: "",
  },
  replyFormVisible: false,
  replyForm: {
    id: null,
    replyContent: "",
  },
  selectedIds: [],
  classList: [],
  selectedClassId: "", // 添加用于筛选的班级 ID
  chooseStatus: "",
  user: JSON.parse(localStorage.getItem('xm-user') || '{}')
});
const uploadUrl = import.meta.env.VITE_BASE_URL + "/files/upload";
request.get('/classInfo/selectAll').then(res => { data.classList = res.data })
// 加载数据
const load = () => {
  request
      .get("/feedback/selectPage", {
        params: {
          content: data.content,
          pageNum: data.pageNum,
          pageSize: data.pageSize,
          classId: data.selectedClassId,
          ...(data.chooseStatus !== "" ? { status: data.chooseStatus } : {}) // 仅当 chooseStatus 不为空时添加 status 参数
        },
      })
      .then((res) => {
        if (res.code === '200') {
          data.tableData = res.data?.list || [];
          data.total = res.data?.total;
        }
      });
};

// 重置查询条件
const reset = () => {
  data.content = ""
  data.chooseStatus=""
  data.selectedClassId=""
  load();
};

// 添加举报信息
const handleAdd = () => {
  data.addForm = { content: "", attachment: "" };
  data.addFormVisible = true;
};

const saveAdd = () => {
  request.post("/feedback/add", data.addForm).then((res) => {
    if (res.code === '200') {
      ElMessage.success("添加成功");
      data.addFormVisible = false;
      load();
    }
  });
};

// 回复举报内容
const handleReply = (row) => {
  data.replyForm = { id: row.id, replyContent: "" };
  data.replyFormVisible = true;
};

const saveReply = () => {
  request.put("/feedback/update", data.replyForm).then((res) => {
    if (res.code === '200') {
      ElMessage.success("回复成功");
      data.replyFormVisible = false;
      load();
    }
  });
};

// 删除单个记录
const del = (id) => {
  ElMessageBox.confirm("确认删除此条记录？", "提示", {
    type: "warning",
  }).then(() => {
    request.delete(`/feedback/delete/${id}`).then((res) => {
      if (res.code === '200') {
        ElMessage.success("删除成功");
        load();
      }
    });
  });
};

// 批量删除
const delBatch = () => {
  if (data.selectedIds.length === 0) {
    ElMessage.warning("请先选择需要删除的记录");
    return;
  }
  ElMessageBox.confirm("确认删除选中的记录？", "提示", {
    type: "warning",
  }).then(() => {
    request.delete("/feedback/delete/batch", { data: data.selectedIds }).then((res) => {
      if (res.code === '200') {
        ElMessage.success("批量删除成功");
        load();
      }
    });
  });
};

// 上传相关
const beforeUpload = (file) => {
  const isValidType = file.type === "application/x-zip-compressed" || file.type === "application/rar";
  if (!isValidType) {
    ElMessage.error("只能上传zip或rar文件");
  }
  return isValidType;
};

const handleUploadSuccess = (response) => {
  if (response && response.data) {
    data.addForm.attachment = response.data;
    ElMessage.success("附件上传成功");
  }
};

const handleUploadError = () => {
  ElMessage.error("附件上传失败");
};

// 处理表格选中变化
const handleSelectionChange = (rows) => {
  data.selectedIds = rows.map((item) => item.id);
};

load();
</script>
